package mysql

import (
	"database/sql"
	"errors"
	"github.com/didi/gendry/manager"
	"github.com/didi/gendry/scanner"
	_ "github.com/go-sql-driver/mysql"
	"time"
)

type Management struct {
	db *sql.DB
	tx *sql.Tx
}

func (m *Management) Close() error {
	if m.db != nil {
		return m.db.Close()
	}
	return nil
}

var (
	charset      = "utf8"
	parseTime    = true
	timeout      = 1 * time.Second
	readTimeout  = 2 * time.Second
	writeTimeout = 2 * time.Second
	port         = 3306
	//tag          = "ddb"
)

func GetMySqlManagement(host, dbName, user, password string, arguments map[string]interface{}) (management *Management, err error) {
	mana := manager.New(dbName, user, password, host)

	if arguments != nil {
		if tmp, ok := arguments["charset"].(string); ok {
			charset = tmp
		}
		if tmp, ok := arguments["parseTime"].(bool); ok {
			parseTime = tmp
		}
		if tmp, ok := arguments["timeout"].(time.Duration); ok {
			timeout = tmp
		}
		if tmp, ok := arguments["readTimeout"].(time.Duration); ok {
			readTimeout = tmp
		}
		if tmp, ok := arguments["writeTimeout"].(time.Duration); ok {
			writeTimeout = tmp
		}
		if tmp, ok := arguments["tag"].(string); ok && len(tmp) > 0 {
			scanner.SetTagName(tmp)
		}
		if tmp, ok := arguments["port"].(int); ok && tmp > 0 {
			port = tmp
		}
	}
	mana.Set(
		manager.SetCharset(charset),
		manager.SetParseTime(parseTime),
		manager.SetTimeout(timeout),
		manager.SetReadTimeout(readTimeout),
		manager.SetWriteTimeout(writeTimeout),
	).Port(port)
	db, err := mana.Open(true)
	if err != nil {
		return
	}
	if db == nil {
		err = errors.New("db is nil")
		return
	}
	management = &Management{db: db}
	return
}
